<template>
    <el-form :model="form" label-width="auto" style="max-width: 600px" v-if="showPassword">
        <el-form-item :label="`${form.active === 'email' ? '邮箱' : '手机'}验证码`">
            <el-input v-model="form.code" placeholder="请输入验证码">
                <template #append>
                    <div class="time">{{ timer }}</div>
                </template>
            </el-input>
        </el-form-item>
        <el-form-item label="新密码">
            <el-input v-model="form.newPassword" placeholder="请输入新密码" type="password" clearable show-password />
        </el-form-item>
        <el-form-item label="确认密码">
            <el-input v-model="form.confirmPassword" placeholder="请输入确认密码" type="password" clearable show-password />
        </el-form-item>
        <el-form-item>
            <div class="form-btn">
                <el-button type="primary" @click="onSubmit">提交</el-button>
                <el-button type="danger" @click="onCancel">取消</el-button>
            </div>
        </el-form-item>
    </el-form>
    <el-tabs v-model="form.active" stretch lazy type="border-card" v-else>
        <el-tab-pane label="邮箱验证" name="email">
            <el-form :model="form" label-width="auto" style="max-width: 600px">
                <el-form-item label="邮箱地址">
                    <el-input v-model="form.email" placeholder="请输入邮箱地址">
                        <template #append>
                            <el-button @click="sendCode" type="warning">发送验证码</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
        </el-tab-pane>
        <el-tab-pane label="短信验证" name="phone">
            <el-form :model="form" label-width="auto" style="max-width: 600px">
                <el-form-item label="手机号">
                    <el-input v-model="form.phone" placeholder="请输入手机号">
                        <template #append>
                            <el-button @click="sendCode" type="warning">发送验证码</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
        </el-tab-pane>
    </el-tabs>
</template>

<script setup lang="ts">
import { reactive, inject, ref, onBeforeUnmount } from "vue";
import { debounce } from "lodash-es";

//获取自定义全局方法
const { axios, baseURL, encrypt, emitter } = inject<any>("method");

//忘记密码 Form表单
const form = reactive<any>({
    active: "email",
    phone: "",
    email: "",
    code: "",
    newPassword: "",
    confirmPassword: "",
});

//展示密码信息
const showPassword = ref(false);

//忘记密码时间，单位分钟
const totalTime = ref<number>();
const timer = ref<string>();
const intervalId = ref();

//发送验证码
const sendCode = debounce(async () => {
    if (form.active == "email" && form.email?.trim() == "") {
        emitter.emit("msg-error", "请输入邮箱地址");
    } else if (form.active == "phone" && form.phone?.trim() == "") {
        emitter.emit("msg-error", "请输入手机号");
    } else {
        const data = await axios.post(`${baseURL}/sendCodeByEmailOrPhone`, form);
        if (data.data.success) {
            showPassword.value = true;
            initPasswordTime(data.data.data.time);
            emitter.emit("msg-success", data.data.data.data);
        } else {
            emitter.emit("msg-error", data.data.message);
        }
    }
}, 200);

//初始化时间
const initPasswordTime = (time: number) => {
    totalTime.value = time * 60;
    intervalId.value = setInterval(() => {
        //时间减一
        totalTime.value = totalTime.value! - 1;
        //分钟
        const minute = Math.floor(totalTime.value / 60);
        //秒
        const seconds = Math.floor(totalTime.value % 60);
        if (totalTime.value >= 60) {
            timer.value = `${minute}分${seconds > 9 ? seconds : "0" + seconds}秒`;
        } else if (totalTime.value >= 0) {
            timer.value = `${seconds > 9 ? seconds : "0" + seconds}秒`;
        } else {
            clearInterval(intervalId.value);
        }
    }, 1000);
};

//使用defineEmits注册一个自定义事件
const emit = defineEmits(["onCancel"]);

//修改密码取消
const onCancel = () => {
    emit("onCancel");
    showPassword.value = false;
    Object.keys(form).forEach((item: string) => (form[item] = ""));
    form.active = "email";
};

//修改密码
const onSubmit = debounce(async () => {
    if (form.code?.trim() == "") {
        emitter.emit("msg-error", "请输入验证码");
    } else if (form.newPassword?.trim() == "") {
        emitter.emit("msg-error", "请输入新密码");
    } else if (form.confirmPassword?.trim() == "") {
        emitter.emit("msg-error", "请输入确认密码");
    } else if (form.newPassword != form.confirmPassword) {
        emitter.emit("msg-error", "两次密码不一致");
    } else {
        emitter.emit("loading-open", { target: ".el-form", text: "修改中..." });
        const param = {
            active: form.active,
            phone: form.phone,
            email: form.email,
            code: form.code,
            newPassword: encrypt(form.newPassword),
            confirmPassword: encrypt(form.confirmPassword),
        };
        const data = await axios.put(`${baseURL}/updatePasswordByEmailOrPhone`, param);
        if (data?.data?.success) {
            emitter.emit("msg-success", data.data.data);
            onCancel();
        } else {
            emitter.emit("msg-error", data.data.message);
        }
        emitter.emit("loading-close");
    }
}, 200);

//清除定时器
onBeforeUnmount(() => {
    clearInterval(intervalId.value);
    onSubmit.cancel();
    sendCode.cancel();
});
</script>

<style scoped lang="less">
.form-btn {
    text-align: center;
    margin-right: 20px;
    width: 100%;

    .el-button {
        width: 25%;
    }
}
</style>
